package com.cx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 可以拦截所有的页面，但是登陆页面必须的放行
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = {"*.jsp","*.html","*.do"})
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String requestPath = request.getServletPath();
        // login2/login.html

        // 精确匹配使用equals判断
        if(requestPath.contains("login.html") || requestPath.contains("user/login") || requestPath.contains("register/register") || requestPath.contains("register.html")) {
            // 直接放行
            chain.doFilter(req, resp);
        } else {
            // 访问其他的页面
            // 判断登录的依据，是session中保存了用户的登录信息
            HttpSession session = request.getSession();
            Object userName = session.getAttribute("user");

            if(userName != null) {
                // 说明用户已登录
                chain.doFilter(req, resp);
            } else {
                // 说明用户未登录，跳转到登录页面
                HttpServletResponse response = (HttpServletResponse) resp;
                response.sendRedirect("login.html");
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
